package ru.nsu.ccfit.kalah.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import ru.nsu.ccfit.kalah.R;
import ru.nsu.ccfit.kalah.database.DatabaseManager;
import ru.nsu.ccfit.kalah.game.*;
import ru.nsu.ccfit.kalah.view.field.FieldView;
import ru.nsu.ccfit.kalah.view.field.SelectListener;

import java.util.List;

public class GameActivity extends Activity {

    public static final String EXTRA_FIRST_PLAYER_NAME = "firstPlayerName";
    public static final String EXTRA_SECOND_PLAYER_NAME = "secondPlayerName";
    public static final String EXTRA_TWO_PLAYERS_FLAG = "twoPlayersFlag";

    private boolean twoPlayersFlag;

    FieldView fieldView;


    Player southPlayer = new Player() {


        @Override
        public void requestMove() {
            //    Toast.makeText(getBaseContext(), "South player move", Toast.LENGTH_SHORT).show();
            statusTextView.setText(String.format("%s player move", getIntent().getStringExtra(EXTRA_FIRST_PLAYER_NAME)));

        }
    };


    Player northManPlayer = new Player() {


        @Override
        public void requestMove() {
            //  Toast.makeText(getBaseContext(), "North player move", Toast.LENGTH_SHORT).show();
            statusTextView.setText(String.format("%s player move", getIntent().getStringExtra(EXTRA_SECOND_PLAYER_NAME)));

        }
    };


    GameController gameController;
    TextView statusTextView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        twoPlayersFlag = getIntent().getBooleanExtra(EXTRA_TWO_PLAYERS_FLAG, false);

        statusTextView = (TextView) findViewById(R.id.status);
        SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE);
        Player aiPlayer = new AiPlayer(preferences.getInt(SettingsActivity.PREFERENCE_LEVEL, SettingsActivity.DEFAULT_AI_LEVEL)) {
            @Override
            public void requestMove() {
                statusTextView.setText(String.format("%s player move", getIntent().getStringExtra(EXTRA_SECOND_PLAYER_NAME)));
                super.requestMove();
            }
        };
        Player northPlayer = twoPlayersFlag ? northManPlayer : aiPlayer;


        gameController = new GameController(southPlayer, northPlayer);


        fieldView = (FieldView) findViewById(R.id.field);
        gameController.setMoveAnimatorListener(fieldView);
        EndOfGameListener endOfGameListener = new EndOfGameListener() {
            @Override
            public void onGameEnded(int first, int second) {
                Score score = new Score();
                score.setFirstPlayer(getIntent().getStringExtra(EXTRA_FIRST_PLAYER_NAME));
                score.setSecondPlayer(getIntent().getStringExtra(EXTRA_SECOND_PLAYER_NAME));
                score.setFirstScore(first);
                score.setSecondScore(second);
                DatabaseManager.insertScore(getBaseContext(), score);
                AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this);
                boolean isFirstWinner = score.getFirstScore() > score.getSecondScore();
                String message = String.format("%s has won! %d vs %d", isFirstWinner ? score.getFirstPlayer() : score.getSecondPlayer(), isFirstWinner ? score.getFirstScore() : score.getSecondScore(), !isFirstWinner ? score.getFirstScore() : score.getSecondScore());
                if (score.getFirstScore() == score.getSecondScore()) {
                    message = "Draw!";
                }
                builder.setMessage(message);
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        finish();
                    }
                });
                builder.show();
            }
        };

        gameController.setEndOfGameListener(endOfGameListener);
        // fieldView.setField(gameController.getField());
        fieldView.setSelectListener(new SelectListener() {
            @Override
            public void onSelected(int index) {
                if (index > 7) {
                    index -= 7;
                    if (twoPlayersFlag && gameController.isReady() && gameController.isFirstPlayer()) {
                        Toast.makeText(getBaseContext(), "Invalid move!", Toast.LENGTH_SHORT).show();
                        return;
                    }

                } else {
                    if (gameController.isReady() && !gameController.isFirstPlayer()) {

                        Toast.makeText(getBaseContext(), "Invalid move!", Toast.LENGTH_SHORT).show();
                        return;
                    }

                }
                gameController.makeMove(index);
            }
        });

        gameController.startGame();

    }
}